package view;
import dao.*;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import commen.*;
@WebServlet("/blog_list.html")
public class blog_Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        //检测是否登录
//        HttpSession session=req.getSession(false);
//        if(session==null){
//            System.out.println("session为空");
//            resp.sendRedirect("login.html");
//            return;
//        }
//        User user= (User) session.getAttribute("user");
        User user=check.checkSession(req);
        if(user==null){
            resp.sendRedirect("login.html");
            return;
        }
        //1.从数据库拿到所有博客
        List<blog> blogs= blogdao.getAllBlog();
        int count=blogdao.count(user.getUserId());
        //2.进行模板引擎渲染
        ServletContext context=this.getServletContext();
        TemplateEngine engine= (TemplateEngine) context.getAttribute("engine");
        WebContext webContext=new WebContext(req,resp,context);
        webContext.setVariable("blogs",blogs);
        webContext.setVariable("user",user);
        webContext.setVariable("count",count);
        String html=engine.process("blog_list",webContext);
//        System.out.println(html);
        resp.getWriter().write(html);
    }
}
